<?php
namespace Api\Model;
use Think\Model;

class UserScoreModel extends Model{
	public $autoCheckFields = false;

	/**
	 * 更新积分
	 * @param  [type]  $user_id   用户ID
	 * @param  integer $score     得分
	 */
	public function update_credit($user_id, $score = 1){
		$where['user_id'] = $user_id;
		
		$model = D('User');
		if($score > 0){
			$model->where($where)->setInc('score', $score);
		}else{
			$model->where($where)->setDec('score', abs($score));
		}
	}
	/**
	 * 根据规则更新积分
	 * @param  [type] $user_id  更新用户ID
	 * @param  string $desc_key 描述规则
	 * @param  int    $multiple 倍数
	 */
	public function role_update_score($user_id){
		if(!$user_id){
			return false;
		}
		//获取诚信度规则配置
		$score_config = C('score_config');

		$role = CONTROLLER_NAME . '/' . ACTION_NAME;
		$role = strtolower($role);

		$config   = $score_config[$role];
		
		$params_field = $config['params_id'];
		$params_id    = $_REQUEST[$params_field];
		$role_md5     = md5($role . ($params_id ? '|' . $params_id : ''));

		//得分
		$score = $config['score'];
		//过滤
		if(!$score || !$role){
			return false;
		}
		//有积分ID判断
		if($config['params_id'] && !$params_id){
			return false;
		}
		//总数量限制
		$total_limit = $config['total_limit'];
		if($total_limit > 0 && is_numeric($total_limit)){
			unset($where);
			$where['user_id']  = $user_id;
			$where['role_md5'] = $role_md5;
			$count = D('ScoreLogs')->where($where)->count();
			if(D('ScoreLogs')->where($where)->count() >= $total_limit){
				return false;
			}
		}
		//每月数量限制
		$month_limit = $config['month_limit'];
		if($month_limit > 0 && is_numeric($month_limit)){
			unset($where);
			$where['user_id']  = $user_id;
			$where['role_md5'] = $role_md5;
			$where['ym']       = date('Ym');
			if(D('ScoreLogs')->where($where)->count() >= $month_limit){
				return false;
			}
		}
		//每天数量限制
		$day_limit = $config['day_limit'];
		if($day_limit > 0 && is_numeric($day_limit)){
			unset($where);
			$where['user_id']  = $user_id;
			$where['role_md5'] = $role_md5;
			$where['ymd']      = date('Ymd');
			if(D('ScoreLogs')->where($where)->count() >= $day_limit){
				return false;
			}
		}

		//更新积分
		$this->update_credit($user_id, $score);
		//记录日志
		$this->record_log($user_id, $role, $role_md5, $score, $params_id);

		return $score;
	}
	/**
	 * 记录日志
	 * @param  [type] $user_id 用户ID
	 * @param  [type] $role    规则
	 * @param  [type] $score   积分
	 */
	public function record_log($user_id, $role, $role_md5, $score, $params_id = ''){
		$data['user_id']     = $user_id ? $user_id : 0;
		$data['role']        = $role;
		$data['role_md5']    = $role_md5;
		$data['score']       = $score;
		$data['params_id']   = $params_id ? $params_id : 0;
		$data['ym']          = date('Ym');
		$data['ymd']         = date('Ymd');
		$data['create_time'] = time();
		D('ScoreLogs')->add($data);
	}
}
?>